from selenium import webdriver
import time
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver import ActionChains
class Grap:
    def __init__(self):
        # 设置驱动的路径,这是 selenium4之后的新写法
        self.service = Service(executable_path=r"C:\Program Files\Google\Chrome\Application\chromedriver.exe")
        # 实例化浏览器对象
        self.driver = webdriver.Chrome(service=self.service)

    # ----- # （1）单击鼠标左键 -----
    def click_mouse_test(self):
        self.driver.get('https://www.baidu.com/')
        self.driver.maximize_window()
        # 定位到登录按钮对应的元素
        element = self.driver.find_element(By.ID,'s-top-loginbtn')
        time.sleep(2)
        ActionChains(self.driver).click(on_element=element).perform()
        time.sleep(2)
    
    # ----- （2）鼠标悬停 -----
    def move_to_test(self):
        #导航到百度网页
        self.driver.get('https://www.baidu.com')
        #浏览器窗口最大化
        self.driver.maximize_window()
        #定位需要悬停的元素
        bg_config1=self.driver.find_element(By.XPATH,'//*[@id="s-usersetting-top"]')
        #创建一个ActionChains对象
        actions=ActionChains(self.driver)
        #使用move_to_element()模拟将鼠标悬停在超链接“设置”处,并通过perform()方法来执行操作
        actions.move_to_element(bg_config1).perform()
        time.sleep(10)
        #鼠标悬停时，定位元素，超链接“搜索设置”,然后单击操作
        bg_config2=self.driver.find_element(By.XPATH,"//div/a[@class='setpref first']")
        bg_config2.click()
        #等待5s
        time.sleep(5)
        #关闭浏览器

    # ----- （3）鼠标移动 -----
    def drag_and_drop_test(self):
        self.driver.get('https://portal.fuyunfeng.top/plugins_v2'
           '/index.html#/slider-verify-example')
        # 定位元素
        element = self.driver.find_element(By.XPATH, "//div[@id='circle']")
        # 创建鼠标移动对象
        action = ActionChains(self.driver)
        # 按住鼠标左键
        action.click_and_hold(element)
        # 向右拖曳100像素
        action.drag_and_drop_by_offset(element, 100, 0)
        # 等待2s
        time.sleep(2)
        action.perform()
if __name__ == '__main__':
    g = Grap()
    g.move_to_test()


